package com.linciping.useges.plugin.util;

import com.intellij.psi.*;
import com.linciping.useges.plugin.bean.UsegesNode;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.psi.KtImportList;

public class PsiFileUtil {

    public static boolean hasPsiFileInPsiDirectory(PsiDirectory directory, String fileName) {
        return hasPsiFileInPsiDirectory(directory, fileName, false);
    }

    public static boolean hasPsiFileInPsiDirectory(PsiDirectory directory, String fileName, boolean isDeep) {
        return findPsiFileInPsiDirectory(directory, fileName, isDeep) != null;
    }

    public static PsiFile findPsiFileInPsiDirectory(PsiDirectory directory, String fileName) {
        return findPsiFileInPsiDirectory(directory, fileName, false);
    }

    public static PsiFile findPsiFileInPsiDirectory(PsiDirectory directory, String fileName, boolean isDeep) {
        PsiFile[] psiFiles = directory.getFiles();
        if (psiFiles.length == 0 && !isDeep) return null;
        for (PsiFile psiFile : psiFiles) {
            if (psiFile.getName().equals(fileName)) {
                return psiFile;
            }
        }
        if (!isDeep) {
            return null;
        }
        PsiDirectory[] psiDirectories = directory.getSubdirectories();
        if (psiDirectories.length == 0) return null;
        for (PsiDirectory psiDirectory : psiDirectories) {
            PsiFile result = findPsiFileInPsiDirectory(psiDirectory, fileName, true);
            if (result != null) return result;
        }
        return null;
    }


    public static boolean isAllowJavaFile(PsiJavaFile psiJavaFile) {
        String packageName = psiJavaFile.getPackageName();
        if (packageName.isEmpty()) {
            return false;
        }
        PsiImportList psiImportList = psiJavaFile.getImportList();
        if (psiImportList == null) {
            return false;
        }
        return psiImportList.getImportStatements().length != 0;
    }

    public static boolean isAllowKtFile(KtFile ktFile) {
        String packageName = ktFile.getPackageName();
        if (packageName.isEmpty()) {
            return false;
        }
        KtImportList ktImportList = ktFile.getImportList();
        if (ktImportList == null) {
            return false;
        }
        return ktImportList.getImports().size() != 0;
    }

    public static String getFullName(UsegesNode sourceNode) {
        PsiNamedElement psiNamedElement = sourceNode.getPsiNamedElement();
        if (psiNamedElement instanceof PsiJavaFile) {
            return ProjectFileUtil.getJavaFileFullName((PsiJavaFile) psiNamedElement);
        } else if (psiNamedElement instanceof KtFile) {
            return  ProjectFileUtil.getKtFullName((KtFile) psiNamedElement);
        }
        return null;
    }
}
